<template>
  <!-- 查询条件 -->
  <el-card shadow="hover" class="rd-8">
    <el-form inline :model="queryParams">
      <el-form-item label="讲师名称">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入讲师名称"
          clearable
          class="query_width"
        />
      </el-form-item>
      <el-form-item label="头衔">
        <el-select
          v-model="queryParams.level"
          placeholder="请选择头衔"
          clearable
          class="query_width"
        >
          <el-option label="高级讲师" value="0" />
          <el-option label="首席讲师" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" class="date_width">
        <el-date-picker
          clearable
          value-format="YYYY-MM-DD"
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="getHasTeacher()">
          搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- table -->
  <el-card shadow="hover" class="mt-10 rd-8">
    <template #header>
      <el-button type="primary" icon="Plus" plain @click="handleAdd()">
        新增
      </el-button>
      <el-button
        type="danger"
        icon="Delete"
        plain
        :disabled="selectedUsers.ids.length === 0"
        @click="handleDelete()"
      >
        删除
      </el-button>
    </template>
    <el-table
      :data="tableData"
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        prop="name"
        label="讲师名称"
        width="200"
        align="center"
      />
      <el-table-column prop="avatar" label="头像" width="200" align="center">
        <template #default="{ row }">
          <ImagePreview :width="100" :height="100" :src="row.avatar" />
        </template>
      </el-table-column>

      <el-table-column prop="level" label="头衔" width="200" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.level === '0'">高级讲师</el-tag>
          <el-tag v-else type="danger">首席讲师</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="career" label="资历" width="240" align="center" />
      <el-table-column prop="intro" label="介绍" align="center" width="280">
        <template #default="{ row }">
          <el-popover
            effect="light"
            trigger="hover"
            placement="top"
            width="auto"
          >
            <template #default>
              <div class="w-280 mb-2">
                {{ row.intro }}
              </div>
            </template>
            <template #reference>
              <el-text class="w-280 mb-2" truncated>
                {{ row.intro }}
              </el-text>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        align="center"
      />
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-tooltip content="修改" placement="top">
            <el-button
              type="primary"
              size="small"
              text
              icon="Edit"
              @click="handleEdit(row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              type="primary"
              size="small"
              text
              icon="Delete"
              @click="handleDelete(row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="重置密码" placement="top">
            <el-button
              type="primary"
              size="small"
              text
              icon="Key"
              @click="handleResetPwd(row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt-10"
      v-show="total > 0"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[5, 8, 13, 15]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasTeacher"
      @size-change="getHasTeacher"
    />
  </el-card>

  <!-- 添加或修改用户配置对话框 -->
  <el-dialog
    :title="dialog.title"
    v-model="dialog.visible"
    width="700px"
    align-center
    append-to-body
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="讲师名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入讲师名称"
              maxlength="30"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="头衔" prop="level">
            <el-select v-model="form.level" placeholder="请选择头衔">
              <el-option value="0" label="高级讲师" />
              <el-option value="1" label="首席讲师" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="资历" prop="career">
            <el-input v-model="form.career" placeholder="一句话说明讲师~" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="form.password"
              placeholder="请输入密码"
              type="password"
              show-password
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="头像" prop="userType">
            <CropperImage v-model="form.avatar" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="介绍" prop="intro">
            <el-input
              v-model="form.intro"
              placeholder="请输入介绍"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessageBox, ElMessage } from 'element-plus'
import type { DateModelType, FormInstance, FormRules } from 'element-plus'
import ImagePreview from '@/components/ImagePreview/index.vue'
import CropperImage from '@/components/CropperImage/index.vue'
import { Teacher, TeacherQuery } from '@/api/teacher/type'
import {
  reqAddTeacher,
  reqDeleteTeacher,
  reqResetTeacherPwd,
  reqTeacherPage,
  reqUpdateTeacher,
} from '@/api/teacher'
import { addDateRange } from '@/utils/util'
let queryParams = ref<TeacherQuery>({
  name: undefined,
  level: undefined,
})
let dateRange = ref<[DateModelType, DateModelType]>(['', ''])
let tableData = ref<Array<Teacher>>([])
let pageSize = ref<number>(8)
let pageNum = ref<number>(1)
let total = ref<number>(0)
let selectedUsers = reactive<{ ids: Array<string>; usernames: Array<string> }>({
  ids: [],
  usernames: [],
})

const formRef = ref<FormInstance>()
let dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})
const initForm: Teacher = {
  teacherId: undefined,
  name: '',
  password: '',
  level: '0',
  avatar: undefined,
  intro: undefined,
  delFlag: '0',
  career: undefined,
}
let form = ref<Teacher>({ ...initForm })
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    {
      min: 2,
      max: 20,
      message: '用户名称长度必须介于 2 和 20 之间',
      trigger: 'blur',
    },
  ],
  password: [
    {
      min: 5,
      max: 20,
      message: '用户密码长度必须介于 5 和 20 之间',
      trigger: 'blur',
    },
  ],
})
/* 重置查询 */
const resetQuery = async () => {
  dateRange.value = ['', '']
  queryParams.value = {
    name: undefined,
    level: undefined,
  }
  await getHasTeacher()
}

const handleSelectionChange = (val: Array<Teacher>) => {
  selectedUsers.ids = val.map((item) => item.teacherId) as Array<string>
  selectedUsers.usernames = val.map((item) => item.name)
}

/** 删除按钮操作 */
const handleDelete = async (row?: Teacher) => {
  const userIds = row?.teacherId || selectedUsers.ids
  const userNames = row?.name || selectedUsers.usernames
  try {
    await ElMessageBox.confirm(
      '是否确认删除用户名称为"' + userNames + '"的数据项？',
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
    await reqDeleteTeacher(userIds)
    ElMessage.success('删除成功')
    await getHasTeacher()
  } catch (error) {
    return
  }
}

/** 重置密码按钮操作 */
const handleResetPwd = async (row: Teacher) => {
  try {
    let { value } = await ElMessageBox.prompt(
      '请输入"' + row.name + '"的新密码',
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      },
    )
    await reqResetTeacherPwd(row.teacherId as string, value)
    ElMessage.success('修改成功，新密码是：' + value)
  } catch (error) {
    return
  }
}
/**
 * 重置表单
 */
const resetForm = () => {
  formRef.value?.clearValidate()
  form.value = { ...initForm }
}
/* 新增按钮 */
const handleAdd = () => {
  resetForm()
  dialog.visible = true
  dialog.title = '新增用户'
}
/* 修改按钮 */
const handleEdit = (row: Teacher) => {
  resetForm()
  dialog.visible = true
  dialog.title = '修改用户'
  form.value = row
  // console.log(row)
}
/** 查询用户列表 */
const getHasTeacher = async (pager = 1) => {
  pageNum.value = pager
  let result = await reqTeacherPage(
    pageNum.value,
    pageSize.value,
    addDateRange(queryParams.value, dateRange.value),
  )
  tableData.value = result.rows
  total.value = result.total
  // console.log(result.rows)
}

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false
  resetForm()
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.teacherId
        ? await reqUpdateTeacher(form.value)
        : await reqAddTeacher(form.value)
      ElMessage.success('操作成功')
      dialog.visible = false
      await getHasTeacher()
    }
  })
}

onMounted(() => {
  // 获取table数据
  getHasTeacher()
})
</script>

<style scoped>
.query_width {
  width: 240px;
}
.date_width {
  width: 308px;
}
</style>
